# 创建时间:2023/2/19 0:34
# 创建人:天霄
# 计划 :SenjoTwintail
# 文件 :SoldierPaths.py
# 基于 Python 3.8.2
# ========================================
# 文件简介
# ========================================
from vars import *
import random
from Api import openApi, savings
from BasePygame.Public import flagBox


class SoldierPaths:
    def __init__(self, soldierCode, language, mode='clothes'):
        """一个军士的资源路径，包括图片、声音

        :param soldierCode: 军士代码/服装代码，默认为服装代码
        :param language: 语言（jp/cn）
        :param mode: 代码模式（军士/服装），默认服装
        """
        self.charimage_root = CONST.PATH.CHARIMAGE_ROOT
        self.soldierCode = soldierCode
        if mode not in ('soldier', 'clothes'):
            raise KeyError(f'模式错误！只能为soldier/clothes，然而传入的是{mode}')
        self.mode = mode
        self.touchSoundsData = openApi.getTouchSound(self.soldierCode, language)
        self.dailySoundsData = openApi.getDailySound(self.soldierCode, language)
        self.imagesData = openApi.getAllSkinCharimage(self.soldierCode, 4, ('half', 'rep', 'cut'), self.mode)
        self.clothIconPaths = openApi.getClothesIconPath(self.soldierCode)
        self.initImage = openApi.getPathsCharimage(self.soldierCode, ('half',), mode=self.mode)[0]

    def dressup(self, cloth_code):
        """换装"""
        self.soldierCode = cloth_code
        self.initImage = openApi.getPathsCharimage(self.soldierCode, ('half',), mode=self.mode)[0]
        self.imagesData = openApi.getAllSkinCharimage(self.soldierCode, 4, ('half',), self.mode)
        # image_id, file, nature, code, imgtype, face, facenum, describe = self.imagesData[0]
        imgData = self.imagesData[0]
        face = (CONST.PATH.CHARIMAGE_ROOT / f'{imgData.file}.png', imgData.imgtype)
        return face

    def touch_feedback(self):
        """触摸反馈表情、声音路径"""
        touchwhere = flagBox.fondled_where
        self.imagesData = openApi.getAllSkinCharimage(self.soldierCode, 4, ('half', 'rep', 'cut'), self.mode)
        imagepaths = list()
        soundpaths = list()
        for imgData in self.imagesData:
            imagepaths.append((CONST.PATH.CHARIMAGE_ROOT / f'{imgData.file}.png', imgData.imgtype))
        for sound in self.touchSoundsData:
            soundpaths.append(CONST.PATH.SOUND_ROOT / sound.path)
        try:
            face = random.choice(imagepaths)
            sound = None
            if soundpaths:
                sound = random.choice(soundpaths)
        except Exception as err:
            print(f'发生错误！此时imagesData为：\n{self.imagesData}\n此时touchSoundsData为：{self.touchSoundsData}\n错误为：{err}')
            raise
        del imagepaths, soundpaths
        # print(face)
        return face, sound

    def random_talk(self):
        """随机表情、声音"""
        self.imagesData = openApi.getAllSkinCharimage(self.soldierCode, 4, ('half', 'rep', 'cut'), self.mode)
        imagepaths = list()
        soundpaths = list()
        for imgData in self.imagesData:
            imagepaths.append((CONST.PATH.CHARIMAGE_ROOT / f'{imgData.file}.png', imgData.imgtype))
        for sound in self.dailySoundsData:
            soundpaths.append(CONST.PATH.SOUND_ROOT / sound.path)
        try:
            face = random.choice(imagepaths)
            sound = None
            if soundpaths:
                sound = random.choice(soundpaths)
        except Exception as err:
            print(f'发生错误！此时imagesData为：\n{self.imagesData}\n此时dailySoundsData为：{self.dailySoundsData}\n错误为：{err}')
            raise
        del imagepaths, soundpaths
        # print(face)
        return face, sound

    def refresh_clothIconPath(self):
        """重新获取服装路径"""
        self.clothIconPaths = openApi.getClothesIconPath(self.soldierCode)
        return self.clothIconPaths

    def get_soldierCode(self, anyCode):
        """通过服装code获取军士唯一code"""
        return openApi.getRoleCodeByCode(anyCode)


class AllSoldiersImagesPaths:
    def __init__(self):
        """所有军士的所有图像"""
        # self.allHalfHeads = openApi.getAllHalfHead(soldiderHaveCodeList)
        self.allLovers = savings.get_allLovers()
        self.allHaveMains = list()
        self.soldiderHaveCodeList = list()
        self.allHalfHeads = list()
        self.refresh_halfheads()

    def refresh_halfheads(self):
        """刷新头像路径"""
        self.allHaveMains = savings.get_all_haveMainCodes()
        self.soldiderHaveCodeList = list()
        for code, level, job, exp, bg in self.allHaveMains:
            self.soldiderHaveCodeList.append(code)
        self.allHalfHeads = list()
        _allHalfHeads = openApi.getAllHalfHead(tuple(self.soldiderHaveCodeList))
        '''(name, file, code, job, nature)'''
        for name, file, code, job, nature in _allHalfHeads:
            for hcode, level, hjob, exp, bg in self.allHaveMains:
                if hcode == code:
                    self.allHalfHeads.append((name, file, code, job, nature, level, exp, bg))
                    break
        self.allHalfHeads.sort(key=lambda x: x[0])
        self.allHalfHeads.sort(key=lambda x: x[3])
        self.allHalfHeads.sort(key=lambda x: x[6], reverse=True)
        self.allHalfHeads.sort(key=lambda x: x[5], reverse=True)
        return self.allHalfHeads

    def getcodebycode(self, code):
        """通过任意code获取军士code"""
        return openApi.getCodeByClothcode(code)

    def getInfoBycode(self, code) -> dict:
        """通过任意code获取军士基本信息"""
        info: dict = openApi.getInfoByCode(code)
        self.allLovers = savings.get_allLovers()
        for lover in self.allLovers:
            hcodes = [c['code'] for c in lover['clothes']]
            if code in hcodes:
                info['favorLevel'] = lover['favorLevel']
                info['favorEXP'] = lover['favorEXP']
                info['favorBg'] = lover['favorBg']
                break
        return info

    def getRoleRecordContent(self, anycode, record_type):
        """通过任意code获取军士记录，1犯罪记录/2角色故事"""
        content = openApi.getRoleRecordContentByCode(anycode, record_type)
        if not content: return ''
        elif len(content) == 1: return content[0][-1].content
        return content